#!/usr/bin/env python
# -*- coding: utf8 -*-
#~#######################################################################
#~ Copyright (c) 2008 Burdakov Daniel <kreved@kreved.org>               #
#~                                                                      #
#~ This file is no part of FreQ-bot.                                    #
#~                                                                      #
#~ FreQ-bot is free software: you can redistribute it and/or modify     #
#~ it under the terms of the GNU General Public License as published by #
#~ the Free Software Foundation, either version 3 of the License, or    #
#~ (at your option) any later version.                                  #
#~                                                                      #
#~ FreQ-bot is distributed in the hope that it will be useful,          #
#~ but WITHOUT ANY WARRANTY; without even the implied warranty of       #
#~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        #
#~ GNU General Public License for more details.                         #
#~                                                                      #
#~ You should have received a copy of the GNU General Public License    #
#~ along with FreQ-bot.  If not, see <http://www.gnu.org/licenses/>.    #
#~#######################################################################

import popen2

def vpnstop_handler(t,s,p):
    p = 'sudo /etc/init.d/openvpn stop'
    cmd = "bash -c 'LANG=%s %s' 2>&1"%(config.SH_LANG,p.replace("'","'\\''"))
    p = popen2.Popen3(cmd, True)
    while p.poll() == -1: pass
    s.msg(t, "\n" + ''.join(p.fromchild.readlines()).decode('utf-8'))
bot.register_cmd_handler(vpnstop_handler, '.vpn_stop', 100)

def vpnstart_handler(t,s,p):
    p = 'sudo /etc/init.d/openvpn start'
    cmd = "bash -c 'LANG=%s %s' 2>&1"%(config.SH_LANG,p.replace("'","'\\''"))
    p = popen2.Popen3(cmd, True)
    while p.poll() == -1: pass
    s.msg(t, "\n" + ''.join(p.fromchild.readlines()).decode('utf-8'))
bot.register_cmd_handler(vpnstart_handler, '.vpn_start', 100)

def ifconfig_handler(t,s,p):
    p = '/sbin/ifconfig'
    cmd = "bash -c 'LANG=%s %s' 2>&1"%(config.SH_LANG,p.replace("'","'\\''"))
    p = popen2.Popen3(cmd, True)
    while p.poll() == -1: pass
    s.msg(t, "\n" + ''.join(p.fromchild.readlines()).decode('utf-8'))
bot.register_cmd_handler(ifconfig_handler, '.ifconfig', 100)

def sensors_handler(t,s,p):
    p = 'sensors'
    cmd = "bash -c 'LANG=%s %s' 2>&1"%(config.SH_LANG,p.replace("'","'\\''"))
    p = popen2.Popen3(cmd, True)
    while p.poll() == -1: pass
    s.msg(t, "sensors\n" + ''.join(p.fromchild.readlines()).decode('utf-8'))
bot.register_cmd_handler(sensors_handler, '.sensors', 5)

def ups_handler(t,s,p):
    p = 'upsc yttups@localhost'
    cmd = "bash -c 'LANG=%s %s' 2>&1"%(config.SH_LANG,p.replace("'","'\\''"))
    p = popen2.Popen3(cmd, True)
    while p.poll() == -1: pass
    s.msg(t, "UPS\n" + ''.join(p.fromchild.readlines()).decode('utf-8'))
bot.register_cmd_handler(ups_handler, '.ups', 5)

def yttro_handler(t, s, p):
    a = [u'всенепременьейше',
         u'очень даже может быть',
         u'да ну?',
         u'дадада',
         u'проклятье.. уже?',
         u'подумай хорошо',
         u'ога',
         u'уттро',
         u'да',
         u'утро',
         u'внатури',
         u'угу']
    from random import randint
    from time import sleep
    sleep(randint(0,4))
    s.msg(t, a[randint(0,len(a)-1)])
bot.register_cmd_handler(yttro_handler, u'уттро')

def groupchats_handler(t, s, p):
    q = bot.g.keys()
    q.sort(lambda x, y: len(bot.g[y].items)-len(bot.g[x].items))
    q = ['%s(%s)' % (g, bot.g[g].count()) for g in q]
    q = [i.replace(config.DEFAULT_MUC_SERVER, '') for i in q]
    s.lmsg(t, 'groupchats','\n\t' + u'\n\t'.join(q), len(q))
bot.register_cmd_handler(groupchats_handler, '.groupchats', 100)

def mclean_handler(t, s, p):
    for i in range(23):
        bot.muc.msg('groupchat', s.room.jid, '')
        time.sleep(2.3)
    s.msg('chat', 'done')
bot.register_cmd_handler(mclean_handler, '.mc', 7, 1)

def ping_handler(t, s, p):
 jid = get_jid(s, p)
 typ = get_type(s, p)
 tpl = (jid, get_nick(jid), lang.get('from_you', l=lang.getLang(s.jid)), lang.get('from_me', l=lang.getLang(s.jid)))[typ]
 packet = IQ(bot.wrapper.x, 'get')
 packet.addElement('query', 'jabber:iq:version')
 packet.addCallback(ping_result_handler, t, s, p, tpl, time.time(), typ)
 reactor.callFromThread(packet.send, jid)

def ping_result_handler(t, s, p, tpl, ping_time, typ, x):
 if x['type'] == 'error':
  describe_error(t, s, x, typ)
 elif x['type'] == 'result':
  pong_time = time.time()
  s.lmsg(t, 'pong', tpl, time2str(pong_time-ping_time, False, lang.getLang(s.jid)))
 else: pass

bot.register_cmd_handler(ping_handler, '.pong')

def mueller_handler(t, s, p):
    import locale
    locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')
    import dictdlib
    a = dictdlib.DictDB('/usr/share/dictd/mueller7')
    if type(p) == type(u""):
        p=p.encode('utf-8')
    answer = a.getdef(p)[0]
    if answer!='':
        answer = unicode(answer,'utf-8', errors='ignore')
        s.msg(t,answer)
    else:
        s.msg(t,'no results')
bot.register_cmd_handler(mueller_handler, '.mueller', 5)


def lingvo_handler(t, s, p):
    import locale
    locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')
    import weblingvosoft,sys
    sys.path.insert(0, '/usr/share/opendict')
    a = weblingvosoft.WebLingvoSoft("15")
    if type(p) == type(u""):
        p=p.encode('utf-8')
    b = a.search(p)
    from lib.extra import html2text
    answer = html2text.html2text(b.getTranslation())
    if answer!='':
        answer = unicode(answer,'utf-8', errors='ignore')
        s.msg(t,answer)
    else:
        s.msg(t,'no results')
bot.register_cmd_handler(lingvo_handler, '.lingvoenru', 5)


